package com.tea.modules.java8.thread.semaphore;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 单个许可的控制信号量
 * @author jaymin
 * @since 2022/3/7 0:25
 */
@Slf4j
public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        int state = 2;
        final Semaphore semaphore = new Semaphore(3);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
            executorService.execute(()->{
                try {
                    // 获取许可
                    semaphore.acquire();
                    doSomeThing();
                    // 释放许可
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();

    }

    private static void doSomeThing() {
        log.info("record");
    }
}
